package com.example.item01.filter;

import com.alibaba.fastjson.JSONObject;
import com.example.item01.proj.Result;
import com.example.item01.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


@Slf4j
//@WebFilter(urlPatterns = "/*")
public class DemoFilter implements Filter {


    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest req= (HttpServletRequest)servletRequest;
        HttpServletResponse res=(HttpServletResponse)servletResponse;
        String url = req.getRequestURL().toString();
        if(url.contains("login")){//登录界面
            log.info("url是{}",url);
            filterChain.doFilter(servletRequest,servletResponse);
            return;
        }
        String jwt = req.getHeader("token");

        if(!StringUtils.hasLength(jwt)){//空            为什么不直接length调用
            Result error = Result.error("NOT_LOGIN");
            log.info("jwt令牌为空,无效");
            String jsonString = JSONObject.toJSONString(error);
            res.getWriter().write(jsonString);
            return;
        }
        try {
            JwtUtils.parseJWT(jwt);
        } catch (Exception e) {
            e.printStackTrace();
            log.info("解析错误");
            Result error = Result.error("NOT_LOGIN");
            String jsonString = JSONObject.toJSONString(error);
            res.getWriter().write(jsonString);
            return;
        }
        log.info("令牌合法,放行");
        filterChain.doFilter(servletRequest,servletResponse);
    }

    @Override
    public void destroy() {
        Filter.super.destroy();
    }
}
